import Vue from "vue";
import Vuex from "vuex";
import getters from "./getters";

Vue.use(Vuex);

const actions = {
  addCart(context, payload) {
    return new Promise((resolve, reject) => {
      const oldProduct = context.state.cartList.find((item) => {
        return item.iid === payload.iid;
      });
      if (oldProduct) {
        context.commit("addProductCount", oldProduct);
        // resolve('当前在加一')
      } else {
        context.commit("addProduct", payload);
        // resolve('当前在加商品')
      }
    });
  },
};

const mutations = {
  addProduct(state, payload) {
    payload.count = 1;
    payload.checked = false;
    state.cartList.push(payload);
  },
  addProductCount(state, payload) {
    payload.count++;
  },
};

const state = {
  cartList: [],
};

export default new Vuex.Store({
  actions,
  mutations,
  state,
  getters,
});
